package cn.edu.zjut.mina.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 分配与回收房间号
 * @author 张宇翔
 */
//此方法需要测试专门测试过
public class RoomIdInfo {
	private final static int roomNum = 99999;//共可创建100000个房间
	private static List<String> mUnUsedRoomId = new ArrayList<String>();//未被使用的房间号
	private static boolean isFirst = true;//是否是第一次执行获取房间号的函数
	
	public synchronized static String getRoomId () {//获取房间号
		/**
		 * 初始化静态变量
		 */
		if (isFirst) {
			List<String> tempList = new ArrayList<String>();
			for (int tempRoomId = 0; tempRoomId <= roomNum; tempRoomId++) {
				String roomId = String.valueOf(tempRoomId);
				if (tempRoomId < 10) {
					roomId = "0000" + roomId;
				} else if (tempRoomId < 100) {
					roomId = "000" + roomId;
				} else if (tempRoomId < 1000) {
					roomId = "00" + roomId;
				} else if (tempRoomId < 10000) {
					roomId = "0" + roomId;
				}
				tempList.add(roomId);
			}
			Random random = new Random(System.currentTimeMillis());
			do {
				int randomIndex = Math.abs(random.nextInt(tempList.size()));
				mUnUsedRoomId.add(tempList.remove(randomIndex));
			} while (tempList.size() > 0);
			isFirst = false;
			System.out.println("房间数量 = " + mUnUsedRoomId.size());
		}
		
		synchronized (mUnUsedRoomId) {
			if (mUnUsedRoomId.size() > 0) {//如果还有空余房间则把房间号分配出去
				String roomId = mUnUsedRoomId.get(0);
				mUnUsedRoomId.remove(0);//将房间号分配出去
				return roomId;
			} else {
				return "";
			}
		}
	}
	
	public static void giveBack (String roomId) {//归还房间号
		synchronized (mUnUsedRoomId) {
			mUnUsedRoomId.add(roomId);
		}
	}
}
